package com.payment.web.controller.app;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.base.Const;
import com.payment.common.type.MoneyTypeStatus;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.MerchantWallet;
import com.payment.system.domain.MoneyChange;
import com.payment.system.domain.SystemConfig;
import com.payment.system.service.IMerchantDayService;
import com.payment.system.service.IMerchantMonthService;
import com.payment.system.service.IMerchantService;
import com.payment.system.service.IMerchantWalletService;
import com.payment.system.service.IMoneyChangeService;
import com.payment.system.service.IStoreService;
import com.payment.system.service.ISystemConfigService;

/**
 * @author fuzhili
 * @Description: app分享处理
 * @date 2019/1/28 10:09
 */
@Controller
@RequestMapping("/app/share")
public class ShareController {

    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IMoneyChangeService moneyChangeService;
    @Autowired
    private IMerchantDayService dayServicer;
    @Autowired
    private IMerchantMonthService monthServiceService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private ISystemConfigService configService;
    @Autowired
    private IMerchantWalletService merchantWalletService;

    /**
     * 分享栏 联系人，意向客户列表(直接客户)
     *
     * @param merchantPhone 手机号
     * @param pageNum       页数
     * @param pageSize      每页条数
     * @return
     */
    @RequestMapping("/directCustomerList")
    @ResponseBody
    public AjaxResult directCustomerList(String merchantPhone, Integer pageNum, Integer pageSize) {
        return merchantService.directCustomerList(merchantPhone, pageNum, pageSize);
    }

    /**
     * app端 分享跳转注册页面
     *
     * @param parentPhone
     * @return
     */
    @RequestMapping(value = "/registerPage/{parentPhone}")
    public String register(@PathVariable("parentPhone") String parentPhone, ModelMap mmap) {
        if (StringUtils.isEmpty(parentPhone)) {
            return "缺失参数";
        }
        String parent = parentPhone.substring(0, 3);
        String phone = parentPhone.substring(parentPhone.length() - 4, parentPhone.length());
        mmap.put("parentPhone", parent + "****" + phone);
        mmap.put("parentPhoneNow", parentPhone);
        return "/fenxiang/Invitation";
    }

    /**
     * app端 跳转到下载app页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/download")
    public String download() {
        return "/fenxiang/download";
    }

    /**
     * 分享界面 查询商户统计记录(我的团队,我的收益，我的交易 )
     * <p>
     * 用户ID
     *
     * @return
     */
    @PostMapping(value = "/upLevel")
    @ResponseBody
    public AjaxResult upLevel() {
        String upLevel = "";
        try {
            upLevel = RedisPoolUtil.get("upLevel");
        } catch (Exception e) {
            upLevel = "nil";
        }
        if (upLevel == null || "".equals(upLevel) || "nil".equals(upLevel)) {
            SystemConfig config = configService.selectSystemConfigByConfigCode("upLevel");
            upLevel = config.getConfigValue();
            RedisPoolUtil.setex("upLevel", config.getConfigValue(), 86400);
        }
        return AjaxResult.successAndData("成功", JSONArray.parse(upLevel));
    }

    /**
     * 分享界面 查询商户统计记录(新变动模块,我的团队模块,我的收益，我的交易 )
     *
     * @param merchantId 用户ID
     * @return
     */
    @PostMapping(value = "/statisticRecord")
    @ResponseBody
    public AjaxResult selectMerchantStatisticRecordByMerchantId(String merchantId) {
        return merchantService.selectMerchantStatisticRecordByMerchantId(merchantId);
    }

    /**
     * 新变动列表
     *
     * @param phone
     * @param day
     * @return
     */
    @PostMapping(value = "/newChangesList")
    @ResponseBody
    public AjaxResult newChangesList(String phone, String day) {
        return merchantService.newChangesList(phone, day);
    }

    /**
     * @param phone
     * @param merchantPhone
     * @return
     */
    @PostMapping(value = "/parentList")
    @ResponseBody
    public AjaxResult selectMerchantParentListByParentPhone(String phone) {
        return merchantService.selectMerchantListByParentPhone(phone);
    }

    /**
     * 我的团队列表
     *
     * @param phone    手机号
     * @param pageNum  页数
     * @param pageSize 每页条数
     * @return
     */
    @PostMapping(value = "/myTeam")
    @ResponseBody
    public AjaxResult selectMerchantMyTeam(String phone, Integer pageNum, Integer pageSize) {
        return merchantService.selectMerchantMyTeam(phone, pageNum, pageSize);
    }


    /**
     * 我的团队二级列表
     *
     * @param phone
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @PostMapping(value = "/myTeamTwo")
    @ResponseBody
    public AjaxResult myTeamTwo(String phone) {
        return merchantService.myTeamTwo(phone);
    }

    /**
     * 我的收益类型 暂不用
     *
     * @return
     */
    @RequestMapping(value = "/profitType")
    @ResponseBody
    public AjaxResult selectProfitType() {
        List<String> list = new ArrayList<String>();
        //收款、还款（ 、充值 、升级  团队管理 管理收益 境外、卡测评、升级返现（
//    A("10A", "收款"), B("10B", "还款"), C("10C", "充值"),
//    D("10D", "升级"), Z("10Z", "升级返现"), E("10E", "团队管理"),
//    F("10F", "提现"), H("10H", "办卡"), I("10I", "卡测评"),
//    J("10J", "境外"), K("10K", "空卡"), M("10M", "管理收益"),
//    A2("20A", "碰一碰");
        list.add(MoneyTypeStatus.A.getCode() + ";" + MoneyTypeStatus.A.getInfo());
        list.add(MoneyTypeStatus.B.getCode() + ";" + MoneyTypeStatus.B.getInfo());
        list.add(MoneyTypeStatus.C.getCode() + ";" + MoneyTypeStatus.C.getInfo());
        list.add(MoneyTypeStatus.D.getCode() + ";" + MoneyTypeStatus.D.getInfo());
        list.add(MoneyTypeStatus.E.getCode() + ";" + MoneyTypeStatus.E.getInfo());
        list.add(MoneyTypeStatus.M.getCode() + ";" + MoneyTypeStatus.M.getInfo());
        list.add(MoneyTypeStatus.J.getCode() + ";" + MoneyTypeStatus.J.getInfo());
        list.add(MoneyTypeStatus.I.getCode() + ";" + MoneyTypeStatus.I.getInfo());
        list.add(MoneyTypeStatus.A2.getCode() + ";" + MoneyTypeStatus.A2.getInfo());
        list.add(MoneyTypeStatus.Z.getCode() + ";" + MoneyTypeStatus.Z.getInfo());
        list.add(MoneyTypeStatus.K.getCode() + ";" + MoneyTypeStatus.K.getInfo());
//        list.add(MoneyTypeStatus.F.getCode() + ";" + MoneyTypeStatus.F.getInfo());
        return AjaxResult.successAndData("成功", list);
    }

    /**
     * 收益列表 暂不用
     *
     * @param type
     * @param pageNum
     * @param pageSize
     * @param merchantId
     * @return
     */
    @PostMapping(value = "/profitList")
    @ResponseBody
    public AjaxResult selectProfitList(String type, Integer pageNum, Integer pageSize, String merchantId) {
        return moneyChangeService.selectProfitList(type, pageNum, pageSize, merchantId);
    }

    /**
     * app收益列表
     *
     * @param pageNum
     * @param pageSize
     * @param merchantId
     * @param time       时间
     * @param timeEnd
     * @return
     */
    @PostMapping(value = "/newProfitList")
    @ResponseBody
    public AjaxResult newProfitList(Integer pageNum, Integer pageSize, String merchantId, String time, String timeEnd) {
        return moneyChangeService.newProfitList(pageNum, pageSize, merchantId, time, timeEnd);
    }

    @PostMapping(value = "/storeList")
    @ResponseBody
    public AjaxResult storeList(Integer pageNum, Integer pageSize, String city) {
        return AjaxResult.successAndData("成功", storeService.selectStoreList(city, pageNum, pageSize));
    }

    @PostMapping(value = "/redMoney")
    @ResponseBody
    public AjaxResult redMoney(String merchantId) {
        /* 获取当天时间 */
        DateFormat df = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
        List<MoneyChange> li = moneyChangeService.selectListByMoneyTypeAndStutas(merchantId, "10D", "10A");
        List<Map<String, Object>> ml = new ArrayList<>();
        BigDecimal money = BigDecimal.ZERO;
        for (MoneyChange moneyChange : li) {
            Calendar day = Calendar.getInstance();
            day.setTime(moneyChange.getCreateTime());
            day.add(Calendar.DATE, 7);
            Date endDate = day.getTime();
            Map<String, Object> map1 = new HashMap<>();
            money = money.add(moneyChange.getTrxAmt());
            map1.put("time1", endDate);
            map1.put("money", moneyChange.getTrxAmt());
            ml.add(map1);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("money", money);
        map.put("list", ml);
        return AjaxResult.successAndData("成功", map);
    }

    /**
     * 我的交易 日/月
     *
     * @param type
     * @param pageNum
     * @param pageSize
     * @param merchantId
     * @return
     */
    @PostMapping(value = "/transactionList")
    @ResponseBody
    public AjaxResult selectTransactionList(String type, Integer pageNum, Integer pageSize, String merchantId) {
        if (StringUtils.isEmpty(type) || pageNum == null || pageSize == null || StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "缺失必要参数");
        }
        if ((Const.DayORMonthEnum.DAY.getCode()).equals(type)) {
            return dayServicer.selectMerchantDayListByMerchantId(pageNum, pageSize, merchantId);
        } else if ((Const.DayORMonthEnum.MONTH.getCode()).equals(type)) {
            return monthServiceService.selectMerchantMonthListByMerchantId(pageNum, pageSize, merchantId);
        } else {
            return AjaxResult.error(2, "暂不支持此请求类型，如有疑问请咨询客服人员！");
        }
    }

    /**
     * 报表统计
     *
     * @param merchantId
     * @return
     */
    @PostMapping(value = "/reportFormTotal")
    @ResponseBody
    public AjaxResult selectReportFormTotal(String merchantId, String phone) {
        return monthServiceService.selectReportFormTotal(merchantId, phone);
    }

    /**
     * app端 跳转到身份认证失败说明页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/authentication")
    public String authentication() {
        return "/fenxiang/authentication";
    }

    /**
     * app端 跳转到用户协议
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/agreement")
    public String agreement() {
        return "/fenxiang/xieyi";
    }

    /**
     * app端 跳转到 活动规则
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/rule")
    public String rule() {
        return "/fenxiang/rule";
    }

    /**
     * 商城积分兑换现金：支付密碼支付
     *
     * @param merchantId 商户id
     * @return
     */
    @PostMapping("/shoppingExchangeCashByPwd")
    @ResponseBody
    public AjaxResult shoppingExchangeCashByPwd(String merchantId, String productId, String pwd) {
        try {
            return merchantService.shoppingExchangeCashByPwd(merchantId, productId, pwd);
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 积分兑换成功 》详情
     *
     * @param merchantId
     * @param orderId
     * @return
     */
    @RequestMapping("/shoppingExchangeCashDetails")
    @ResponseBody
    public AjaxResult shoppingExchangeCashDetails(String merchantId, String orderId) {
        return moneyChangeService.shoppingExchangeCashDetails(merchantId, orderId);
    }

    /**
     * 积分明细列表 商城积分兑换/充值分润
     *
     * @param merchantId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/shoppingScoreList")
    @ResponseBody
    public AjaxResult shoppingScoreList(String merchantId, Integer pageNum, Integer pageSize) {
        return moneyChangeService.selectShoppingScoreList(merchantId, pageNum, pageSize);
    }


    /**
     * 积分明细列表 商城积分兑换/充值分润
     *
     * @param merchantId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/getVipSubsidy")
    @ResponseBody
    public AjaxResult getVipSubsidy(String merchantId) {
        MerchantWallet mw = merchantWalletService.selectMerchantWalletByMerchantId(merchantId);
        String vipReturnConfig = "";
        try {
            vipReturnConfig = RedisPoolUtil.get("vipReturnConfig");
        } catch (Exception e) {
            vipReturnConfig = "nil";
        }
        if (vipReturnConfig == null || "nil".equals(vipReturnConfig) || "".equals(vipReturnConfig)) {
            SystemConfig config = configService.selectSystemConfigByConfigCode("vipReturnConfig");
            RedisPoolUtil.setex("vipReturnConfig", config.getConfigValue(), 86400);
            vipReturnConfig = config.getConfigValue();
        }
        JSONObject jsonConfig = JSONObject.parseObject(vipReturnConfig);
        JSONObject numMoney = jsonConfig.getJSONObject("num");
        Map<String, Object> map = new HashMap<>();
        map.put("vipMoney", mw.getVipMoney());//冻结金额
        map.put("releaseVipMoney", mw.getReleaseVipMoney());//释放金额
        map.put("skNum", mw.getSkNum());//刷卡数
        map.put("numMoney", numMoney);//数量对应的金额 对象  {20:40,40:80,60:120}   
        return AjaxResult.successAndData("成功", map);
    }
}
